package com.share.dymamic.datasource;

import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;

public class DynamicDataSource extends AbstractRoutingDataSource {
	
	@Override
	protected Object determineCurrentLookupKey() {
		String dataSourceLookupKey = DataSourceContextHolder.getDataSource();
		return dataSourceLookupKey;
	}

	@Override
	public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {
		super.setDataSourceLookup(dataSourceLookup);
	}

	@Override
	public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
		super.setDefaultTargetDataSource(defaultTargetDataSource);
	}

	@Override
	public void setTargetDataSources(Map<Object, Object> targetDataSources) {
		super.setTargetDataSources(targetDataSources);
		// without afterPropertiesSet, datasource can't be changed.
		super.afterPropertiesSet();
	}
	
	/**
	 * get original datasources
	 * @return
	 * */
	@SuppressWarnings("unchecked")
	public Map<Object, Object> getTargetDataSources() {
		Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
		Object objValue = ReflectionUtils.getFieldValue("targetDataSources", this.getClass().getSuperclass(), this);
		if (objValue instanceof Map) {
			targetDataSources = (Map<Object, Object>) objValue;
		}
		return targetDataSources;
	}
	
	/**
	 * add new datasource
	 * @param dataSourceName
	 * @param dataSource
	 * */
	public void addDataSource(Object dataSourceName, Object dataSource) {
		Map<Object, Object> targetDataSources = getTargetDataSources();
		if (!targetDataSources.containsKey(dataSourceName)) {
			targetDataSources.put(dataSourceName, dataSource);
		}
		// without afterPropertiesSet, new datasource wouldn't take effect.
		super.afterPropertiesSet();
	}
}
